layui.define(['element', 'table', 'ksUtil', 'layer', 'tableFilter', 'load', 'axios'], function(exports){
  var table = layui.table
    , element = layui.element
    , utils = layui.ksUtil
    , $ = layui.jquery
    , layer = layui.layer
    , tableFilter = layui.tableFilter
    , load = layui.load
    , axios = layui.axios
    , tableIns
    , filter
    , DTree;

  var btnGroup = [
    '<button class="layui-btn layui-btn-sm search-btn" id="copyBtn" lay-event="copy" style="display: none"><i class="layui-icon layui-icon-list"></i>复制</button>',
    '<button class="layui-btn layui-btn-sm layui-btn-normal search-btn" id="addBtn" lay-event="add" style="display: none"><i class="layui-icon layui-icon-add-circle-fine"></i>新增</button>',
    '<button class="layui-btn layui-btn-sm layui-btn-normal search-btn" id="editBtn" lay-event="update" style="display: none"><i class="layui-icon layui-icon-edit"></i>编辑</button>',
    '<button class="layui-btn layui-btn-sm layui-btn-danger search-btn" id="delBtn" lay-event="delete" style="display: none"><i class="layui-icon layui-icon-delete"></i>删除</button>',
  ];

  var defaultConfig = {
    type: 'tableFilter',
    tableFilter: {},
    isSync: true,//左边为树时，表格只加载根节点数据
    tree: {
      searchUrl: '',
      addAllNode: true,//是否要添加“显示全部”节点
      icon: "2",  //修改二级图标样式
      elem: '#dTree',
      dataStyle: "layuiStyle",  //使用layui风格的数据格式
      dataFormat: "list",  //配置data的风格为list
      clickFun: null,//节点点击事件
      clickWhere: function(id){// 点击节点后，传给search的参数
        if(id == '0'){
          return {'search.parent_isNull': ''}
        }else{
          return {'search.parent.id_eq': id}
        }
      },
      line: true,  // 显示树线
      toolbar: true, // 开启工具栏
      width: '100%',
      height: 'full-55',
      scroll: "#treeDiv", // 工具栏绑定div
      toolbarShow: [], // 工具栏自带的按钮制空
      menubar: true,
      menubarTips: {
        toolbar: ["moveDown", "moveUp"],  // 指定工具栏吸附的menubar按钮
        group: [] // 按钮组制空
      },
      done: function(data, obj){
        $("#searchBox").unbind().change(function(){
          var value = $("#searchBox").val();
          if(value.length > 1){
            var flag = DTree.searchNode(value); // 内置方法查找节点
            if(!flag){
              layer.msg.error("该名称节点不存在！");
            }
          }else if(value.length === 0){
            DTree.menubarMethod().refreshTree(); // 内置方法刷新树
          }
        });
      }
    },
    id: '',
    elem: '#listTable',
    url: '',
    cols: [[]],
    fields: null,
    page: {
      limit: 20,
      limits: [20, 50, 100, 500, 1000]
    },
    otherBtn: [], // 默认按钮之外的按钮，暂时未使用，使用toolbar
    resourceCode: '',
    height: 'full-55',
    toolbar: '#toolbar',
    response: {
      statusCode: 200 //重新规定成功的状态码为 200，table 组件默认为 0
      , countName: 'total' //规定数据总数的字段名称，默认：count
      , dataName: 'data' //规定数据列表的字段名称，默认：data
    },
    request: {
      pageName: 'page',
      limitName: 'size'
    },
    where: {},
    active: {
      add: '',
      update: '',
      view: '',
      delete: ''
    },
    breadcrumbs: [],
    popup: {
      width: '100%',
      height: '100%'
    },
    btns: [],
    event: {
      add: function(){
        var _config = search.config
          , url = _config.active.add || _config.resourceCode + '_form.html';
        url = changeParams(url, 'add', null, _config);
        layer.openWindow('添加', url, _config.popup.width, _config.popup.height);
      },
      update: function(data){
        if(data.length !== 1){
          layer.msg.error('请选择一行编辑');
          return;
        }
        var _config = search.config
          , url = _config.active.update || _config.resourceCode + '_form.html'
          , d = data[0];
        url = changeParams(url, 'edit', d, _config);
        layer.openWindow('编辑', url, _config.popup.width, _config.popup.height);
      },
      delete: function(data){
        if(data.length === 0){
          layer.msg.error('请至少选择一行');
          return;
        }
        var ids = [];
        for(var dataKey in data){
          ids.push(data[dataKey].id);
        }
        var _config = search.config;
        if(_config.active.delete){
          layer.confirm('是否删除?', function(){
            var url = _config.active.delete;
            if(url.endsWith('/')){
              url += ids.join(',');
            }else{
              url += '/' + ids.join(',');
            }
            utils.delete(url).done(function(result){
              location.reload();
            });
          });
        }else{
          layer.msg.sad('没有配置删除请求');
        }
      },
      copy: function(data){
        if(data.length !== 1){
          layer.msg.error('请选择一行复制');
          return;
        }
        var _config = search.config
          , url = _config.active.update || _config.resourceCode + '_form.html'
          , d = data[0];
        url = changeParams(url, 'copy', d, _config);
        layer.openWindow('编辑', url, _config.popup.width, _config.popup.height);
      }
    },
    rowEvent: {},
    afterInit: null,
    doneEvent: null
  };

  function changeParams(url, type, data, _config){
    // 处理树节点参数
    if(url.indexOf('{tree.') > -1){
      url = url.replace('{tree.id}', _config.tree.nowNode && _config.tree.nowNode.nodeId || '');
      url = url.replace('{tree.name}', _config.tree.nowNode && _config.tree.nowNode.context || '');
    }
    url = utils.addUrlParam(url, 'type', type);
    if(type !== 'add'){
      // 处理动态参数
      var params = utils.getDynamicParam(url);
      layui.each(params, function(i, param){
        var expression = param.substring(1, param.indexOf('}'));
        var data = eval(expression);
        url = url.replace('{' + expression + '}', data);
      });
      url = utils.addUrlParam(url, 'id', data.id);
    }
    return url;
  }

  var search = {
    btnGroup: btnGroup,
    getSelect: function(){
      var checkStatus = table.checkStatus(this.config.id);
      return checkStatus.data;
    },
    config: defaultConfig,
    getTree: function(){
      var that = this;
      return that.config.tree;
    },
    reload: function(where){
      var _config = search.config;
      var w = $.extend({}, _config.where, where);
      tableIns.reload({where: w, page: {curr: 1}});
    },
    render: function(){
      var that = this;
      that.config = $.extend(true, {}, defaultConfig, options);
      var _config = that.config;

      initBreadcrumbs(_config);
      initTable(_config);
      initFilter(_config);
      initTree(_config.tree);

      if(typeof _config.afterInit === 'function'){
        _config.afterInit(_config);
      }

      //监听行双击事件
      table.on('rowDouble(listTable)', function(obj){
        var _config = search.config
          , url = _config.active.view || _config.resourceCode + '_view.html';
        url = utils.addUrlParam(url, 'type', 'view');
        url = utils.addUrlParam(url, 'id', obj.data.id);
        layer.openWindow('查看', url, _config.popup.width, _config.popup.height);
      });
      //监听工具按钮事件
      table.on('toolbar(listTable)', function(obj){
        var checkStatus = table.checkStatus(obj.config.id)
          , _event = obj.event
          , data = checkStatus.data;
        if(typeof _config.event[_event] === 'function'){
          _config.event[_event](data);
        }
      });
      //监听行工具按钮事件
      table.on('tool(listTable)', function(obj){
        var data = obj.data, //获得当前行数据
          layEvent = obj.event, //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
          tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）
        if(typeof _config.rowEvent[layEvent] === 'function'){
          _config.rowEvent[layEvent](data, tr);
        }
      });

      //监听排序事件
      table.on('sort(listTable)', function(obj){
        var where = {
          'sort': obj.field + ',' + obj.type
        };
        search.reload(where);
      });
      return that;
    }
  };

  function initTree(_config){
    if(_config.searchUrl || _config.searchData){
      load('dtree', function(){
        var dtree = layui.dtree
          , elem = _config.elem.replace('#', '');

        search.config.tree.plugin = dtree;

        function bindTreeEvent(){
          // 点击节点触发回调，其中obj内包含丰富的数据
          dtree.on("node('" + elem + "')", function(obj){
            var data = obj.param
              , id = data.nodeId;
            var where = search.config.tree.clickWhere(id);
            // 清空原有的搜索条件
            search.reload(where);
            search.config.tree.nowNode = data;
          });
        }

        if(_config.searchUrl){
          utils.get(_config.searchUrl, _config.searchData)
            .done(function(res){
              var rows = res.data;
              if(_config.addAllNode){
                rows.splice(0, 0, {id: '0', title: '显示根节点', parentId: ''});
              }
              _config.data = rows;
              DTree = dtree.render(_config);
              search.config.tree.DTree = DTree;
              bindTreeEvent();
            });
        }else if(_config.searchData && _config.searchData.length > 0){
          DTree = dtree.render(_config);
          search.config.tree.DTree = DTree;
          // 点击节点触发回调，其中obj内包含丰富的数据
          bindTreeEvent();
        }else{
          layer.msg.error('树型结构参数异常！');
        }
      })
    }
  }

  function initFilter(_config){
    if(_config.type === 'tableFilter'){
      var filterConfig = {
        elem: _config.elem,
        mode: 'api',
        id: _config.id
      };
      $.extend(true, filterConfig, _config.tableFilter);
      filter = tableFilter.render(filterConfig);
    }
  }

  function initTable(_config){
    var tableCof = {
      id: _config.id,
      elem: _config.elem,
      url: _config.url,
      cols: _config.cols,
      page: _config.page,
      height: _config.height,
      toolbar: _config.toolbar,
      defaultToolbar: ['filter'],
      cellMinWidth: 100,
      loading: true,
      autoSort: false,
      response: _config.response,
      request: _config.request,
      headers: _config.headers,
      done: function(res, curr, count){
        var btn = _config.btns;

        function initBtn(btn){
          if(btn !== 'all'){
            for(var i in btn){
              $("#" + btn[i]).show();
            }
            $(".search-btn:hidden").remove();
          }else{
            $(".search-btn").show();
          }
          if(filter){
            filter.reload()
          }
        }

        //获取按钮权限
        if(_config.resourceCode){
          axios.get(API.PERMISSION + _config.resourceCode)
            .then(res => {
              initBtn(res.data);
            });
        }

        if(typeof _config.doneEvent === 'function'){
          var that = this.elem.next();
          _config.doneEvent(res, that);
        }
      }
    };
    if(_config.tree.searchUrl && _config.isSync){
      tableCof.where = $.extend(true, {'search.parent_isNull': ''}, _config.where);
    }else{
      tableCof.where = _config.where;
    }
    tableIns = table.render(tableCof);
  }

  function initBreadcrumbs(_config){
    //初始化导航模板
    var breadcrumbs = _config.breadcrumbs;
    if(breadcrumbs && breadcrumbs.length > 0){
      var html = [];
      layui.each(breadcrumbs, function(index, item){
        if(index == breadcrumbs.length - 1){
          html.push('<a href="javascript:location.replace(location.href)"><cite>' + item + '</cite></a>');
        }else{
          html.push('<a><cite>' + item + '</cite></a>');
        }
      });
      $("span.layui-breadcrumb")[0].innerHTML = html.join('');
      element.render('breadcrumb');
    }
  }

  exports('ksSearch', search);
});
